package ace.cmp.data.methodname.method.name.sql.entity.resolver.impl.property;

import ace.cmp.data.methodname.method.name.sql.core.enums.SqlCommandTypeEnum;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityMapping;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Optional;

/**
 * @author caspar
 * @date 2023/2/18 11:17 如果方法最后一个参数为对象类型参数，则开始解析实体查询元数据
 */
public class SelectQueryPropertyLastInputParameterResolverImpl
    extends AbstractSelectQueryPropertyResolver {

  public SelectQueryPropertyLastInputParameterResolverImpl(
      SqlCommandTypeEnum sqlCommandType, Method method, EntityMapping entityMapping) {
    super(sqlCommandType, method, entityMapping);
  }

  @Override
  protected Class resolveClass() {
    Optional<Parameter> parameterOptional = this.getLastParameter();
    if (parameterOptional.isEmpty()) {
      return null;
    }
    try {
      Class cls = Class.forName(parameterOptional.get().getParameterizedType().getTypeName());
      if (this.isNotCustomClass(cls)) {
        return null;
      }
      return cls;
    } catch (Exception ex) {

    }
    return null;
  }

  private Optional<Parameter> getLastParameter() {
    Parameter[] parameters = this.getMethod().getParameters();
    if (parameters.length == 0) {
      return Optional.empty();
    }
    return Optional.of(parameters[parameters.length - 1]);
  }
}
